/**
 * vivo-xpro6
 *
 * @author flh0909@qq.com
 * @create 15/11/21.
 */

(function ($) {
    var animationend = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',
        page_stime = 0,
        misstion_nums = {"0":"2","1":"4","2":"9","3":"8"};

    var pageConfig = {
        page2: {hasHeader: true},
        page3: {hasHeader: true},
        page4: {hasHeader: true},
        page5: {hasHeader: true},
        page6: {hasHeader: true}
    };

    //webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend

    function _init() {
        _registerEvents();
    }

    $(document).on('touchmove', function (e) {
        e.preventDefault();
    });

    function _registerEvents() {

        _initLoadingNums();

        // 预加载图片
        $('.body').preLoading({
            imgList: IMAGES,
            imgready: function (value) {

                var percent = Math.ceil(value * 100);
                $('#j_loading_val').text(percent + '%');
                $('.loading-bar-val').css({
                    width: percent + '%'
                });
            },
            allready: function () {
                _pageNext();
                //$('.body').data('page', 6).css({transform: 'translate3d(0,-600%,0)'});
                //document.getElementById('j_music').pause();
                //setTimeout(_test, 1000);
            }
        });

        $('.body-music').tap(function () {
           $(this).toggleClass('ani-music');
            if($(this).hasClass('ani-music')) {
                document.getElementById('j_music').play();
            }else{
                document.getElementById('j_music').pause();

            }
        });

        // page1 next
        $('.page1-btn').tap(function () {
            $('.page1-bg').addClass('ani-room-bg').one(animationend, function () {
                _pageNext()

            });
        });

        // page2 扫描指纹
        $('.page2-circle-scan').longTap(function () {
            $('.page2-circle-scan-light').addClass('ani-scan-light').one(animationend, function () {
                var data = _getMisstionData(0);
                data.time = '0.4';
                stopPage2Rotate();
                data.desc = '你仅用' + data.time + '秒就完成急速指纹识别';
                data.title = data.time + 's';
                _showPopup(
                    $.template(TMPL.misstion, {
                        data: data
                    }),
                    _pageNext
                );
            });
        });

        // page3 射击
        $('.page3-shoot').tap(function () {
            var data = _getMisstionData(1);
            data.time = '0.1';
            data.desc = '你仅用' + data.time + '秒急速对焦无人机';
            data.title = data.time + 's';

            $('.page3-shoot-shadow').addClass('ani-shoot-shadow').attr('data-ani', 'ani-shoot-shadow');

            $('.page3-shoot-target').each(function () {
                var ani = $(this).show().data('ani-tem');
                $(this).addClass(ani).attr('data-ani', ani);
            });


            setTimeout(function () {
                _showPopup(
                    $.template(TMPL.misstion, {
                        data: data
                    }),
                    _pageNext
                );
            }, 2000);

        });

        // page4 划圈能量
        var baseX = 0, baseY = 0, posX = 0, posY = 0, currentRotate = 0, circleRotate = 0;
        var $circle = $('.page4-circle'), $circleBar = $('.page4-bar-wrapper');
        $('.page4-toucher')
            .on('touchstart', function (event) {

                baseX = $circle.offset().left + $circle.width() / 2;
                baseY = $circle.offset().top + $circle.width() / 2;
                var touchPros = event.touches[0];
                currentRotate = _getRotate(baseX, baseY, touchPros.pageX, touchPros.pageY);
                console.log('start', currentRotate);
                return false;
            })
            .on('touchmove', function (event) {
                var touchPros = event.touches[0];
                posX = touchPros.pageX;
                posY = touchPros.pageY;

                var curRot = _getRotate(baseX, baseY, posX, posY);
                //console.log('move', curRot, currentRotate);
                var con1 = (curRot > currentRotate && currentRotate > 10),
                    con2 = (curRot < 10 && currentRotate > 350 && curRot + 360 > currentRotate);
                //console.log('con',con1,con2);
                if (con1 || con2) {
                    if (curRot < currentRotate) {
                        curRot += 360;
                    }
                    circleRotate += curRot - currentRotate;
                    //console.log('circleRotate', circleRotate);
                    currentRotate = curRot >= 360 ? curRot - 360 : curRot;
                    var rotateDegStr = 'rotate(' + circleRotate + 'deg)';
                    $circle.css({
                        'transform': rotateDegStr,
                        '-ms-transform': rotateDegStr,
                        '-moz-transform': rotateDegStr,
                        '-webkit-transform': rotateDegStr,
                        '-o-transform': rotateDegStr
                    });

                    var barVal = Math.floor(circleRotate / (360 ) * 100);
                    $circleBar.height(barVal + '%');
                    // 能量条满了
                    if (barVal >= 100 && !$circle.hasClass('on')) {
                        //$('.page4-toucher').off('touchmove');
                        $('.page4-circle-move').remove();
                        $('.page4-circle').addClass('on');
                        setTimeout(_goPage5, 1000);
                    }

                } else {
                    currentRotate = curRot;
                }
                event.preventDefault();
            });

        // page5 启动4G
        $('.page5 .btn-off').tap(function () {
            if ($(this).hasClass('btn-on')) {
                return;
            }
            $(this).removeClass('btn-off').addClass('btn-on');

            var width = Math.floor($('.bar-red').width() / $('.process-bar').width() * 100) + '%';
            $('.process-bar').html('<div class="process-bar-val bar-green">\
                <span class="bar-effect"></span>\
                </div>');
            $('.bar-green').width(width).addClass('ani-bar-green').one(animationend, function () {
                $('.page5-mission').removeClass('loading');
                $('.page5-mission-title').text('mission complete');
                $('.page5-mission-desc').html($.template(TMPL.loading4G, _getMisstionData(3)));
                setTimeout(function () {
                    _pageNext()
                }, 2000);
            });

            //
        });

        // page6 滑动数字
        $('.page6-nums .nums-item')
            .swipeUp(function (event) {
                var $ul = $(this).find('ul');
                var mt = ($ul.data('mt') || 0) - 1;
                if (mt ==-10) {
                    mt+=11;
                    $ul.removeClass('transition').css('marginTop', mt * 120).addClass('transition');
                    mt--;
                }
                    $ul.css('marginTop', mt * 120).data('mt', mt);

                _checkNum($(this).data('index'), mt);
                event.preventDefault();
                //console.log(mt,$ul.data('mt'));
            })
            .swipeDown(function (event) {
                var $ul = $(this).find('ul');
                var mt = ($ul.data('mt') || 0) + 1;
                if (mt ==1) {
                    mt-=11;
                    $ul.removeClass('transition').css('marginTop', mt * 120).addClass('transition');
                    //$ul.addClass('transition');
                    mt++;
                }
                $ul.css('marginTop', mt * 120).data('mt', mt);
                _checkNum($(this).data('index'), mt);
                event.preventDefault();
            })
            .each(function (index) {
                $(this).data('index', index);
                $(this).find('ul').addClass('transition');
            });


        // page6  next
        $('.page6-action a').tap(function () {
            if ($('.status-item.on').length === 4) {
            //if (1 > 0) {
                $(this).hide();
                $('.page6-arrow').hide();
                $('.page6 [data-ani-tem]').each(function () {
                    var ani = $(this).show().data('ani-tem');
                    $(this).addClass(ani).attr('data-ani', ani);
                });
                setTimeout(function () {
                    $('.page6').html('');

                }, 2000);
                $('.page7').addClass('ani-page7');
                _pageNext();
            } else {
                //没有选择对
                alert('密码错误');
            }
        });

        // page7 完成任务
        $('.page7-action a').tap(function () {
			location.href='http://shop.vivo.com.cn/wap/activities-X6.html';
          
        });

    }

    var page2RotateTimer = null;
    pageConfig.page2.afterRender = function () {
        var $sector = $('.sector'),
            $sectorLight = $('.sector-light');
        var r = -56, s = -90, max = 35 * 3 - 56;

        var timer = setInterval(function () {
            r += 3;
            s += 3;
            if (r > max) {
                clearInterval(timer);
                pageConfig.page2.afterRender();
            }

            var tranStr = 'rotate(' + r + 'deg) skew(' + s + 'deg)';
            $sector.css({
                'transform': tranStr,
                '-ms-transform': tranStr,
                '-moz-transform': tranStr,
                '-webkit-transform': tranStr,
                '-o-transform': tranStr
            });
            var tranStr2 = 'skew(' + (-s) + 'deg) rotate(' + (-r) + 'deg)';
            $sectorLight.css({
                'transform': tranStr2,
                '-ms-transform': tranStr2,
                '-moz-transform': tranStr2,
                '-webkit-transform': tranStr2,
                '-o-transform': tranStr2
            });
        }, 100);

    };

    function stopPage2Rotate() {
        if (page2RotateTimer) {
            $('.page2-circle-rotate').show();
            $('.sector').remove();
            clearInterval(page2RotateTimer);
        }
    }

    /**
     * 初始化数字
     * @private
     */
    function _initLoadingNums() {
        var $source = $('.j_loading_source');
        var text = [];
        for (var i = 0; i < 1000; i++) {
            text.push('011100101111011010101110010111101101011101110010111100100101111111011100101111001001011111');
        }
        $source.text(text.join('') + '');

        //var typing = new Typing({
        //    source: $source[0],
        //    output: $source.siblings('.j_print_output')[0],
        //    delay: 50
        //});
        //typing.start();
    }

    /**
     * 检测结果
     * @param index
     * @param val
     * @private
     */
    function _checkNum(index, val) {
        if (misstion_nums[index] == Math.abs(val)) {
            $('.page6-status .status-item').eq(index).addClass('on');
        } else {
            $('.page6-status .status-item').eq(index).removeClass('on');
        }
    }

    function _goPage5() {
        var data = _getMisstionData(2);
        data.desc = '双引擎闪充·两倍充电速度';
        data.title = '100%';
        _showPopup(
            $.template(TMPL.misstion, {
                data: data
            }),
            function () {
                _pageNext();
                setTimeout(function () {
                    var $source = $('.j_loading_source');
                    var typing = new Typing({
                        source: $source[0],
                        output: $source.siblings('.j_print_output')[0],
                        delay: 100
                    });
                    typing.start();
                }, 1000);
            }
        );
    }

    /**
     * 获取角度
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @returns {number}
     * @private
     */
    function _getRotate(x1, y1, x2, y2) {
        var x = Math.abs(x1 - x2);
        var y = Math.abs(y1 - y2);
        var z = Math.sqrt(x * x + y * y);
        var rotat = Math.round((Math.asin(y / z) / Math.PI * 180));

        // 第一象限
        if (x2 >= x1 && y2 <= y1) {
            rotat = 360 - rotat;
        }
        // 第二象限
        else if (x2 <= x1 && y2 <= y1) {
            rotat = 180 + rotat;
        }
        // 第三象限
        else if (x2 <= x1 && y2 >= y1) {
            rotat = 180 - rotat;
        }
        // 第四象限
        else if (x2 >= x1 && y2 >= y1) {
            rotat = rotat;
        }
        return rotat; //真实的角度
    }

    /**
     * 任务提示
     * @param body
     * @param nextFn
     * @private
     */
    function _showPopup(body, nextFn) {
        var $html = $($.template(TMPL.popup, {body: body}));
        $('body').append($html);
        $html.find('.popup-action-next').tap(function () {
            nextFn();
            _closePopup();
        });
    }

    /**
     * 关闭
     * @private
     */
    function _closePopup() {
        $('.popup').remove();
    }

    /**
     * 获取任务密码
     * @param index  任务索引 [0-3]
     * @returns {obj}
     * @private
     */
    function _getMisstionData(index) {
        //var num = Math.floor(Math.random() * 9) + 1;
        var num = misstion_nums[index];
        var time = Math.floor((new Date().getTime() - page_stime) / 1000 * 10) / 10;
        return {
            num: num,
            time: time
        };
    }

    /**
     * 显示下一页
     * @private
     */
    function _pageNext() {


        var $body = $('.body'),
            pageIndex = ($body.data('page') || 0),
            $page = null;
        pageIndex++;
        $page = $('.page' + pageIndex);
        var _pageConfig = pageConfig['page' + pageIndex];
        setTimeout(function () {
            if (_pageConfig && _pageConfig.hasHeader) {
                $('.body-header').html('<div class="mission' + (pageIndex) + '"></div>');
                $('.body-footer').html($page.find('.step').html()).show();
            } else {
                $('.body-header').html('');
                $('.body-footer').html('').hide();
            }


            $('.page' + pageIndex + ' [data-ani],.body-footer  [data-ani]').addClass(function () {
                return $(this).data('ani');
            });
            _print($('.body-footer').find('.j_print_source'));
            _print($page.find('.j_print_source'));

            $('.page' + (pageIndex - 1) + ' [data-ani]').removeClass(function () {
                return $(this).data('ani');
            });

            page_stime = new Date().getTime();

            if (_pageConfig && _pageConfig.afterRender) {
                _pageConfig.afterRender();
            }

        }, 800);

        if (pageIndex < 7) {
            var distance = 100 * pageIndex;
            $('.body').css({
                '-webkit-transform': 'translate3d(0px, -' + distance + '%, 0px)',
                'transform': 'translate3d(0px, -' + distance + '%, 0px)'
            }).data('page', pageIndex);
        }
    }


    /**
     * 打印提示文本
     * @param $source 源
     * @private
     */
    function _print($source) {

        if (!$source.length)
            return;

        var typing = new Typing({
            source: $source[0],
            output: $source.siblings('.j_print_output')[0],
            delay: 200
        });
        typing.start();

    }

    _init();

})(Zepto);

